package com.example.haosiji.activity;

import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.example.haosiji.R;
import com.example.haosiji.app.AppInfo;
import com.example.haosiji.app.DBManager;
import com.example.haosiji.app.haosijiApp;
import com.example.haosiji.beans.DriverInfo;
import com.example.haosiji.listview.RefreshLayout;

import com.example.haosiji.listview.RefreshLayout.onRefreshListener;
import com.example.haosiji.maps.DriverOverlay;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;




public class NearBy extends Activity implements OnClickListener{
	
	protected haosijiApp mApp;
	private BMapManager mMapManager = null;
	
	public MapView mMapView = null;
	private MapController mMapController = null;
	private LocationClient mLocationClient=null;
	
	public MainActivity mParent;
	
	private ImageView imageViewBtn;
	
	private LocationData mLocData;
	private BDLocation location;
	private boolean isRequest = false;
	private boolean isFirstLoc = true;
	private MyLocationOverlay myLocationOverlay = null;
	protected ProgressDialog mWaitDialog;
	protected boolean isWaitingCanceled = false;
	private RelativeLayout layout_map;
	private RefreshLayout lv_driver;
	private ArrayList<Map<String, Object>> listItem;
	private long clickTime = 0;
	
	private boolean isFirst = true;
	
	Button btn;
	
	private DriverOverlay mDriverOverlay;
	private List<DriverInfo> mDriverList;
	
	private LayoutInflater mInflater;
	View localView ;
	TextView driverName;
	
	SimpleAdapter adapter;
	ListView listView;
	
	private Handler mHandler;
	
	
	
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		
		mApp = (haosijiApp) getApplication();
		setContentView(R.layout.activity_find_drivers);

		mMapManager = mApp.getmBMapMan();

		initView();
		initMapView();
		requestLocaton();
	}
	
	
	
	private void location(){
		
		new Thread(){
			public void run(){
				
				//baseUrl             
			    String baseUrl = AppInfo.baseUrl+"/customer/getNearlyDrivers.json"; 
			    
			    try{
			    	
			    	Thread.currentThread().sleep(2000);
			    	
					HttpPost request = new HttpPost(baseUrl);				
					
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
					nameValuePairs.add(new BasicNameValuePair("pointX", mLocData.longitude+""));
					nameValuePairs.add(new BasicNameValuePair("pointY", mLocData.latitude+""));	
					
					request.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8)); 

					/*发送请求并返回结果*/
					HttpResponse httpResponse = new DefaultHttpClient().execute(request);
					
					String retSrc = EntityUtils.toString(httpResponse.getEntity());

					Log.i("11111111111111111", retSrc);
												
					Message msg = new Message();
					if(TextUtils.isEmpty(retSrc)){
						msg.what = 0;
						mHandler.sendMessage(msg);
							
					}else{
						Bundle b = new Bundle();
						b.putString("data",retSrc);
                        msg.setData(b);
                        
                        msg.what = 1;
                        mHandler.sendMessage(msg);	
					}	
			    	
			    }catch(Exception e){	
			    	e.printStackTrace();
			    }
									       	      
			} 
			      
		}.start();
		
		
	}
	
	
	
	public void initView(){
		
		mLocationClient=new LocationClient(mApp); 
		
		layout_map = ((RelativeLayout) findViewById(R.id.map_layout));
		
		lv_driver = (RefreshLayout) findViewById(R.id.refreshable_view1);
		lv_driver.setVisibility(4);
		
		this.mDriverList = new ArrayList();
		
		mInflater = LayoutInflater.from(this);
		
		listItem = new ArrayList<Map<String, Object>>();
		adapter = new SimpleAdapter(this, listItem,R.layout.sijilist, 
				new String[] { "name","number","province","distance","drivingTimes","drivingYears"},
				new int[] { R.id.siji_name,R.id.driver_number,R.id.siji_address,R.id.distance,R.id.drivingTimes,R.id.drivingYears});
		
		listView = (ListView) findViewById(R.id.listsiji);
		listView.setAdapter(adapter);
		
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
				
				TextView name = (TextView)arg1.findViewById(R.id.siji_name);
				TextView phone = (TextView)arg1.findViewById(R.id.driver_number);
				DBManager.saveDriverInfo(name.getText().toString(), phone.getText().toString(), System.currentTimeMillis());
				
				Intent myIntentDial = new Intent("android.intent.action.CALL",Uri.parse("tel:"+phone.getText().toString()));
				startActivity(myIntentDial);
				
			}
		});
		

		lv_driver.setOnRefreshListener(new onRefreshListener() {
			@Override
			public void onRefresh() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				lv_driver.finishRefreshing();
			}
			
		}, 0);
		
		
		mLocData = new LocationData();
		
		imageViewBtn = (ImageView) findViewById(R.id.map_position);
		imageViewBtn.setOnClickListener(this);
		
		mParent = (MainActivity)getParent();
		mParent.btn_map.setEnabled(false);
		mParent.btn_driverlist.setEnabled(true);
		mParent.btn_driverlist.setOnClickListener(this);
		mParent.btn_map.setOnClickListener(this);
		
	}
	
	public void initMapView(){
		
		mHandler = new Handler(){
			public void handleMessage(Message message){
				
			    mWaitDialog.hide();
				
				switch(message.what){
					case 0:
						Toast.makeText(getApplicationContext(), "系统错误！", Toast.LENGTH_SHORT).show();
						break;
					case 1:
						Bundle b = message.getData();
						String msg = b.getString("data");
						listItem.clear();
						try{
							
							JSONArray jsonArray = new JSONArray(msg);
							
							for(int i = 0; i < jsonArray.length(); i++) {
									JSONObject jsonObject = jsonArray.getJSONObject(i);
									
									String name = jsonObject.getString("name");
									String number = jsonObject.getString("mobile");
									String province = "籍贯:"+jsonObject.getString("province");
									String distance = "距离:"+jsonObject.getString("distanceFromCustomer")+"公里";
									String drivingTimes = "代驾:"+jsonObject.getString("drivingTimes")+"次";
									String drivingYears = "驾龄:"+jsonObject.getString("drivingYears")+"年";
									
									if(isFirst){
										if(i == 0){
											Bundle bundle = new Bundle();
											bundle.putString("name", name);
											bundle.putString("number", number);
											bundle.putString("distance", distance);
											bundle.putString("drivingTimes", drivingTimes);
											bundle.putString("drivingYears", drivingYears);
											
											Intent intent = new Intent(NearBy.this,SelectDriver.class);
											intent.putExtra("data", bundle);
											startActivity(intent);
										}
									}
									
									Map<String,Object> item = new HashMap<String,Object>(); 
									item.put("name", name);
									item.put("number", number);
									item.put("province", province);
									item.put("distance", distance);
									item.put("drivingTimes", drivingTimes);
									item.put("drivingYears", drivingYears);
									
									listItem.add(item);
									
									
									
									/*overlay*/
									String pointX = jsonObject.getString("pointX");
									String pointY = jsonObject.getString("pointY");
									
									GeoPoint p1 = new GeoPoint((int) (Double.parseDouble(pointY) * 1E6), (int) (Double.parseDouble(pointX) * 1E6));  
									OverlayItem item1 = new OverlayItem(p1,"item1","item1");
									
									localView = mInflater.inflate(R.layout.driveroverlay, null);
									driverName = (TextView)localView.findViewById(R.id.driver_name);
									driverName.setText(name);
									Bitmap localBitmap = convertViewToBitmap(localView);
									item1.setMarker(new BitmapDrawable(getResources(), localBitmap));
									mDriverOverlay.removeItem(item1);
									mDriverOverlay.addItem(item1); 
									
							}
							
						}catch(Exception e){
							
						}
						
						listView.setAdapter(adapter);
				}
				
				isFirst = false;
			}
		};
		
		
		
		mMapView = ((MapView) findViewById(R.id.mapView));
		
		mMapController = mMapView.getController();
		mMapController.setZoom(15); 
		
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");
		option.setCoorType("bd09ll");
		option.setScanSpan(5000);
		option.disableCache(false); 
		
        mLocationClient.setLocOption(option);  
        
        mLocationClient.registerLocationListener(new BDLocationListenerImpl());
        
        
        myLocationOverlay = new LocationOverlay(mMapView);
		myLocationOverlay.setData(mLocData);

		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();

		/*司机覆盖物*/
		Drawable mark= getResources().getDrawable(R.drawable.overlay_green);
		mDriverOverlay = new DriverOverlay(this,mark, this.mMapView);
		
//		GeoPoint p1 = new GeoPoint((int) (31.112153 * 1E6), (int) (121.378487 * 1E6));  
//		OverlayItem item1 = new OverlayItem(p1,"item1","item1");
//		
//		
//		localView = this.mInflater.inflate(R.layout.driveroverlay, null);
//		driverName = (TextView)localView.findViewById(R.id.driver_name);
//		driverName.setText("上海司机");
//		Bitmap localBitmap = convertViewToBitmap(localView);
//		item1.setMarker(new BitmapDrawable(this.getResources(), localBitmap));
//		mDriverOverlay.addItem(item1); 
//		
//		GeoPoint p2 = new GeoPoint((int) (31.112153 * 1E6), (int) (121.368487 * 1E6));  
//		OverlayItem item2 = new OverlayItem(p2,"item2","item2"); 
//		mDriverOverlay.addItem(item2); 
//		
//		GeoPoint p3 = new GeoPoint((int) (31.122153 * 1E6), (int) (121.378487 * 1E6));  
//		OverlayItem item3 = new OverlayItem(p3,"item3","item3");  
//		mDriverOverlay.addItem(item3); 
//		
//		GeoPoint p4 = new GeoPoint((int) (31.102153 * 1E6), (int) (121.368487 * 1E6));  
//		OverlayItem item4 = new OverlayItem(p4,"item4","item4");  
//		mDriverOverlay.addItem(item4);

		
		mMapView.getOverlays().add(mDriverOverlay);
		
		mMapView.refresh();
	}
	
	public static Bitmap convertViewToBitmap(View paramView){
	    if (paramView == null)
	      return null;
	    paramView.measure(View.MeasureSpec.makeMeasureSpec(0, 0), View.MeasureSpec.makeMeasureSpec(0, 0));
	    paramView.layout(0, 0, paramView.getMeasuredWidth(), paramView.getMeasuredHeight());
	    paramView.buildDrawingCache();
	    return paramView.getDrawingCache();
	  }
	
	protected void showWaiting(int paramInt, String paramString) {
		if (paramInt == 2) {
			if (mWaitDialog == null) {
				mWaitDialog = new ProgressDialog(this);
			}
			this.mWaitDialog
					.setOnCancelListener(new DialogInterface.OnCancelListener() {
						public void onCancel(
								DialogInterface paramAnonymousDialogInterface) {
							NearBy.this.isWaitingCanceled = true;
						}
					});
			this.mWaitDialog
					.setOnDismissListener(new DialogInterface.OnDismissListener() {
						public void onDismiss(
								DialogInterface paramAnonymousDialogInterface) {
							NearBy.this.isWaitingCanceled = false;
						}
					});
			this.isWaitingCanceled = false;
			mWaitDialog.setProgressStyle(0);
			mWaitDialog.setMessage(paramString);
			mWaitDialog.setCancelable(true);
			mWaitDialog.show();
		}

	}

	protected void hideWaiting() {
		if (mWaitDialog != null)
			mWaitDialog.hide();
	}
	
	private void requestLocaton() {
		mApp.checkConnection();
		
		isRequest = true;
		showWaiting(2, "正在获取您的位置...");
		
		mLocationClient.start();
		if ((this.mLocationClient != null)&& (this.mLocationClient.isStarted())){
			mLocationClient.requestLocation();
		}
	
		location();
	}
	
	
	public class BDLocationListenerImpl implements BDLocationListener {

		public void onReceiveLocation(BDLocation location) {
			if (location == null) {
				return;
			}

			NearBy.this.location = location;

			mLocData.latitude = location.getLatitude();
			mLocData.longitude = location.getLongitude();

			mLocData.accuracy = location.getRadius();
			mLocData.direction = location.getDerect();

			myLocationOverlay.setData(mLocData);
			
			if(Double.parseDouble(mLocData.latitude+"") > 1){
				if(isFirst){
					Log.i("121212212212121", mLocData.latitude+"");
					location();
				}
			}
			
			mMapView.refresh();

			if (isFirstLoc || isRequest) {
				mMapController.animateTo(new GeoPoint((int) (location
						.getLatitude() * 1e6),
						(int) (location.getLongitude() * 1e6)));
				isRequest = false;
			}

			isFirstLoc = false;
		}

		public void onReceivePoi(BDLocation poiLocation) {

		}

	}
	
	
	private class LocationOverlay extends MyLocationOverlay {

		public LocationOverlay(MapView arg0) {
			super(arg0);
		}

		@Override
		protected boolean dispatchTap() {
			// showPopupOverlay(location);
			return super.dispatchTap();
		}

		@Override
		public void setMarker(Drawable arg0) {
			super.setMarker(arg0);
		}

	}
	
	protected void onResume() {
		try {
			if (mLocationClient != null) {
				mLocationClient.start();
			}
			if (this.mMapView != null) {
				this.mMapView.onResume();
				requestLocaton();
				this.mMapView.setVisibility(0);
			}
			super.onResume();
			return;
		} catch (Exception localException) {
			while (true)
				localException.printStackTrace();
		}
	}
	
	
	protected void onDestroy() {
		if (mMapView != null){
			mMapView.destroy();
		}	
		mLocationClient.stop();
		super.onDestroy();
	}
	
	
	private void toDriverMap() {
		mParent.btn_map.setEnabled(false);
		mParent.btn_driverlist.setEnabled(true);
		lv_driver.setVisibility(4);
		layout_map.setVisibility(0);
	}
	
	private void toDriverList() {
		mParent.btn_driverlist.setEnabled(false);
		mParent.btn_map.setEnabled(true);
		lv_driver.setVisibility(0);
		layout_map.setVisibility(8);
	}
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.map_position:
			requestLocaton();
			break;
		case R.id.btn_map:
			toDriverMap();
			break;
		case R.id.btn_driver:
			toDriverList();
			break;

		}
	}
	
	public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent){
		if(paramInt == KeyEvent.KEYCODE_BACK){
			
			if(System.currentTimeMillis() - clickTime > 2000){
				Toast.makeText(this, "再按一次退出应用！", Toast.LENGTH_SHORT).show();
				clickTime = System.currentTimeMillis();
			}else{
				mApp.exit();
			}	
		}		
		return false;
	}
	
	


}
